package com.example.demo.utils;


import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 〈一句话功能简述〉<br>
 * 〈cookie工具类〉
 *
 * @author v-zhangkangkang.ea
 * @create 2019/10/16
 * @since 1.0.0
 */
public class CookieUtils {

    /**
     * 设置cookie
     *
     * @param response
     * @param name
     * @param value
     * @param path
     * @param domain
     * @param maxAge
     */
    public static void setCookie(HttpServletResponse response, String name, String value,
                                 String path, String domain, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setSecure(false);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setVersion(0);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 根据名字获取cookie
     *
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        Cookie returnCookie = null;

        if (cookies == null) {
            return returnCookie;
        }

        for (final Cookie thisCookie : cookies) {
            if (thisCookie.getName().equals(name) && !"".equals(thisCookie.getValue())) {
                returnCookie = thisCookie;
                break;
            }
        }

        return returnCookie;
    }


    /**
     * 删除cookie
     * Delete the cookie by setting its maximum age to zero
     *
     * @param response
     * @param cookie
     * @param path
     */
    public static void deleteCookie(HttpServletResponse response,
                                    Cookie cookie, String path) {
        if (cookie != null) {
            cookie.setMaxAge(0);
            cookie.setPath(path);
            response.addCookie(cookie);
        }
    }

    /**
     * 删除cookie
     * Delete the cookie by setting its maximum age to zero
     *
     * @param response
     * @param name
     * @param path
     * @param domain
     */
    public static void deleteCookie(HttpServletResponse response,
                                    String name, String path, String domain) {
        if (!StringUtils.isEmpty(name)) {
            Cookie cookie = new Cookie(name, "");
            cookie.setMaxAge(0);
            cookie.setPath(path);
            cookie.setDomain(domain);
            response.addCookie(cookie);
        }
    }
}